package com.mvvm.store.ui.into;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.device.scanner.configuration.Triggering;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.google.android.material.tabs.TabLayout;
import com.leo.utilspro.utils.ToastUtils;
import com.mvvm.store.R;
import com.mvvm.store.base.BaseActivity;
import com.mvvm.store.base.BaseFragment;
import com.mvvm.store.base.NormalViewModel;
import com.mvvm.store.bean.basebean.IntoMaterialBean;
import com.mvvm.store.bean.basebean.IntoSubmitPramsBean;
import com.mvvm.store.bean.basebean.IntoSubmitResultBean;
import com.mvvm.store.bean.basebean.MaterialInfoBean;
import com.mvvm.store.bean.basebean.ResponModel;
import com.mvvm.store.databinding.FragmentDemoBinding;
import com.mvvm.store.databinding.FragmentIntoManagerBinding;
import com.mvvm.store.roombatabase.IntoInfoDao;
import com.mvvm.store.roombatabase.IntoInforDatabase;
import com.mvvm.store.roombatabase.IntoMaterDatabase;
import com.mvvm.store.roombatabase.IntoMaterialDao;
import com.mvvm.store.ui.into.adaper.MaterialPagerAdapter;
import com.mvvm.store.utils.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Created by leo
 * on 2020/10/21.
 */
public class IntoStorageActivity extends BaseActivity<IntoViewModel, FragmentIntoManagerBinding> {

    private List<Fragment> fragments=new ArrayList<>();

    private List<CharSequence> titleslist=new ArrayList<>();

    private String[] titles = new String[]{"物料信息", "已扫物料标签"};

    private String codeResult="";

    private IntoInfoDao intoInfoDao;
    private IntoMaterialDao intoMaterialDa;
    private List<Boolean> isBool;
    public static boolean isSubmitScan=false;  //扫码提交用的
    public static boolean issubmitSusuce=false;//提交监听
    @Override
    protected int getContentViewId() {
        return R.layout.fragment_into_manager;
    }

    @Override
    protected void processLogic() {
        issubmitSusuce=false;
        isSubmitScan=false;
        //扫码表
        intoInfoDao= IntoInforDatabase.getInstance(this).intoInfoDao();
        //订单表
        intoMaterialDa= IntoMaterDatabase.getInstance(this).materialDao();
        binding.leoTitleBar.bar_right_btn.setVisibility(View.VISIBLE);
        codeResult = getIntent().getStringExtra("codeResult");
        System.out.println("codeResult"+codeResult);
        binding.leoTitleBar.bar_left_btn.setBackgroundResource(R.mipmap.return_images);
        for (int i=0;i<titles.length;i++){
            titleslist.add(titles[i]);
        }
        MaterialInfoFragment materialInfoFragment=MaterialInfoFragment.newInstance("materialInfo",binding.viewPager);
        MaterialSweptFragment materialSweptFragment=MaterialSweptFragment.newInstance("materialSwept",binding.viewPager);
        fragments.add(materialInfoFragment);
        fragments.add(materialSweptFragment);
        MaterialPagerAdapter materialPagerAdapter=new MaterialPagerAdapter(this.getSupportFragmentManager(),fragments,titleslist);
        binding.viewPager.setAdapter(materialPagerAdapter);
        binding.tablayout.setupWithViewPager(binding.viewPager);
        binding.tablayout.setTabMode(TabLayout.MODE_FIXED);
        binding.tablayout.getTabAt(0).select();
    }

    @Override
    protected void setListener() {
        binding.leoTitleBar.bar_left_btn.setOnClickListener(this::onClick);
        binding.leoTitleBar.bar_right_btn.setOnClickListener(this::onClick);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bar_left_btn:
                this.finish();
                break;
            case R.id.bar_right_btn:
               submit();
                break;
            default:
                break;
        }
    }
    private  void  submit(){
        //查询订单表对应的零件是否已经全部扫码完成

        if(isSubmit()){
            SharedPreferences sharedPreferences =this.getSharedPreferences("userInfo", MODE_PRIVATE);
             String userId=sharedPreferences.getString("userId","");
             if("".equals(userId)){
                 //提示他去扫码验证身份
                 ToastUtils.showToast("提交前先请扫码验证身份");
                 isSubmitScan=true;
             }else {

                 IntoSubmitPramsBean intoSubmitPramsBean=new IntoSubmitPramsBean();
                 intoSubmitPramsBean.setDeliveryOrderNo(codeResult);
                 intoSubmitPramsBean.setInStockUser(userId);
                 List< IntoSubmitPramsBean.MaterialList> materialLists=new ArrayList<>();

                 //根据订单号查询订单表的数据
                 List<IntoMaterialBean> intoMaterialBeanListToload= intoMaterialDa.getMaterialInfo(codeResult);
                 for (int i=0;i<intoMaterialBeanListToload.size();i++) {
                     intoSubmitPramsBean.setSupplierName(intoMaterialBeanListToload.get(i).getSupplierName());
                     IntoSubmitPramsBean.MaterialList material=new IntoSubmitPramsBean.MaterialList();
                     material.setBoxNum(intoMaterialBeanListToload.get(i).getRealToPack());
                     material.setPartName(intoMaterialBeanListToload.get(i).getOddName());

                     material.setSnp(intoMaterialBeanListToload.get(i).getSnpNumber());
                     material.setPartCode(intoMaterialBeanListToload.get(i).getOddNumber());
                     material.setAogNum(intoMaterialBeanListToload.get(i).getSumNumber());
                    /* material.setPartCode(intoMaterialBeanListToload.get(i).getOddNumber());
                     material.setSnp(intoMaterialBeanListToload.get(i).getSnpNumber());
                     material.setAogNum(intoMaterialBeanListToload.get(i).getPackNumber());
                     material.setBoxNum(intoMaterialBeanListToload.get(i).getRealToNumber());*/
                     List<String> tagCodeList=new ArrayList<>();
                     //查询零件号对应的标签数据
                  List<MaterialInfoBean> materialInfoBeanList= intoInfoDao.getStockUpInfoByOddNumber(intoMaterialBeanListToload.get(i).getOddNumber());
                  for (int j=0;j<materialInfoBeanList.size();j++){
                      tagCodeList.add(materialInfoBeanList.get(j).getLableNumber());
                  }
                     material.setTagCodeList(tagCodeList);
                  materialLists.add(material);
                 }
                 intoSubmitPramsBean.setMaterialList(materialLists);
                 //设置入库时间
              /*   SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
                    //获取当前时间
                 Date date = new Date(System.currentTimeMillis());
                    String dataTime=simpleDateFormat.format(date);
                 intoSubmitPramsBean.setInStockTime(dataTime);*/
                 System.out.println("入库准备入参-------------------"+intoSubmitPramsBean.toString());
                 //调用接口入库
                 mViewModel.sumbitInto(intoSubmitPramsBean).observe(this,resource->resource.handler(new OnCallback<ResponModel>() {
                     @Override
                     public void onSuccess(ResponModel data) {
                         System.out.println("入库提交返回数据  成功了 ---------------->");
                              ToastUtils.showToast("入库成功!");
                           //  System.out.println("入库提交返回数据---------------->" + data.toString() + "");
                             //提交成功清除数据
                             //先获取订单表的数据获取到订单对应的零件号
                             List<IntoMaterialBean> intoMaterialBeansDelete = intoMaterialDa.getMaterialInfo(codeResult);
                             for (int i = 0; i < intoMaterialBeansDelete.size(); i++) {
                                 //根据订单号查询扫码表数据
                                 List<MaterialInfoBean> materialInfoBeansDelete = intoInfoDao.getAll(intoMaterialBeansDelete.get(i).getOrderNumber());
                                 for (int j = 0; j < materialInfoBeansDelete.size(); j++) {
                                     intoInfoDao.delete(materialInfoBeansDelete.get(j));
                                 }
                                 intoMaterialDa.delete(intoMaterialBeansDelete.get(i));
                             }
                             //删除 Sp里面的本地数据
                             SharedPreferences.Editor spDelete = sharedPreferences.edit();
                             spDelete.clear();
                             spDelete.commit();
                             //将全局扫码的值设置为false
                             IntoStorageActivity.isSubmitScan = false;
                              issubmitSusuce=true;
                             finish();
                     }
                 }));

             }

           // intoSubmitPramsBean.setInStockUser();




        }else {
           ToastUtils.showToast("物料还未完成入库,请检查你的入库信息");

       }
    }

    private boolean isSubmit(){
        isBool=new ArrayList<>();
          List<IntoMaterialBean> intoMaterialBeanList=  intoMaterialDa.getMaterialInfo(codeResult);
          if(intoMaterialBeanList.size()>0){
              for (int i=0;i<intoMaterialBeanList.size();i++){
                  if(intoMaterialBeanList.get(i).getSumNumber()==intoMaterialBeanList.get(i).getRealToNumber()){
                      isBool.add(true);
                  }else {
                      isBool.add(false);
                  }
              }
              for (boolean isBools: isBool){
                  if(!isBools){
                     return false;
                  }
              }
              return true;
          }else {
              ToastUtils.showToast("没有可提交的物料信息");
          }
          return false;
    }

    //--------------------------------------------------------------------------------------------------------------------------------
    private static final String ACTION_DECODE = ScanManager.ACTION_DECODE;   // default action
    private static final String ACTION_DECODE_IMAGE_REQUEST = "action.scanner_capture_image";
    private static final String ACTION_CAPTURE_IMAGE = "scanner_capture_image_result";
    private static final String BARCODE_STRING_TAG = ScanManager.BARCODE_STRING_TAG;
    private static final String BARCODE_TYPE_TAG = ScanManager.BARCODE_TYPE_TAG;
    private static final String BARCODE_LENGTH_TAG = ScanManager.BARCODE_LENGTH_TAG;
    private static final String DECODE_DATA_TAG = ScanManager.DECODE_DATA_TAG;
    private static final String DECODE_CAPTURE_IMAGE_KEY = "bitmapBytes";
    private ScanManager mScanManager = null;
    private static boolean mScanEnable = true;
    private static boolean mScanCaptureImageShow = false;
    private static final int MSG_SHOW_SCAN_RESULT = 1;
    private static final int MSG_SHOW_SCAN_IMAGE = 2;
    private static final int[] SCAN_KEYCODE = {520, 521, 522, 523};

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            System.out.println("onReceive , action:" + action);
            // Get Scan Image . Make sure to make a request before getting a scanned image
            if (ACTION_CAPTURE_IMAGE.equals(action)) {
                byte[] imagedata = intent.getByteArrayExtra(DECODE_CAPTURE_IMAGE_KEY);
                if (imagedata != null && imagedata.length > 0) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(imagedata, 0, imagedata.length);
                    Message msg = mHandler.obtainMessage(MSG_SHOW_SCAN_IMAGE);
                    msg.obj = bitmap;
                    mHandler.sendMessage(msg);
                } else {
                    System.out.println("onReceive , ignore imagedata:" + imagedata);
                }
            } else {
                // Get scan results, including string and byte data etc.
                byte[] barcode = intent.getByteArrayExtra(DECODE_DATA_TAG);
                int barcodeLen = intent.getIntExtra(BARCODE_LENGTH_TAG, 0);
                byte temp = intent.getByteExtra(BARCODE_TYPE_TAG, (byte) 0);
                String barcodeStr = intent.getStringExtra(BARCODE_STRING_TAG);
                if (mScanCaptureImageShow) {
                    // Request images of this scan
                    context.sendBroadcast(new Intent(ACTION_DECODE_IMAGE_REQUEST));
                }
                System.out.println("barcode type:" + temp);
                String scanResult = new String(barcode, 0, barcodeLen);
                // print scan results.
                scanResult = " length：" + barcodeLen + "\nbarcode：" + scanResult + "\nbytesToHexString：" + bytesToHexString(barcode) + "\nbarcodeStr:" + barcodeStr;
                Message msg = mHandler.obtainMessage(MSG_SHOW_SCAN_RESULT);
                msg.obj = barcodeStr;
                mHandler.sendMessage(msg);
            }
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SHOW_SCAN_RESULT:
                    String scanResult = (String) msg.obj;
                    System.out.println("scanResult"+scanResult);
                    printScanResult(scanResult);
                    break;
            }
        }
    };
    /**
     * @param register , ture register , false unregister
     */
    private void registerReceiver(boolean register) {
        if (register && mScanManager != null) {
            IntentFilter filter = new IntentFilter();
            int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
            String[] value_buf = mScanManager.getParameterString(idbuf);
            if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
                filter.addAction(value_buf[0]);
            } else {
                filter.addAction(ACTION_DECODE);
            }
            filter.addAction(ACTION_CAPTURE_IMAGE);

            this.registerReceiver(mReceiver, filter);
        } else if (mScanManager != null) {
            mScanManager.stopDecode();
            this.unregisterReceiver(mReceiver);
        }
    }

    /**
     * byte[] toHex String
     *
     * @param src
     * @return String
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * Intent Output Mode print scan results.
     *
     * @param msg
     */
    private void printScanResult(String msg) {
        if (msg == null) {
            System.out.println("printScanResult , ignore to show msg:" + msg + ",showScanResult");
            return;
        }
        //获取到扫码结果后的处理
        System.out.println("msg---------------------------"+msg);
    }
    private void initScan() {
        mScanManager = new ScanManager();
        mScanManager.switchOutputMode(0);
        boolean powerOn = mScanManager.getScannerState();
        if (!powerOn) {
            powerOn = mScanManager.openScanner();
            if (!powerOn) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("Scanner cannot be turned on!");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                AlertDialog mAlertDialog = builder.create();
                mAlertDialog.show();
            }
        }
    }

    /**
     * ScanManager.getTriggerMode
     *
     * @return
     */
    private Triggering getTriggerMode() {
        Triggering mode = mScanManager.getTriggerMode();
        return mode;
    }

    /**
     * ScanManager.getTriggerLockState
     *
     * @return
     */
    private boolean getlockTriggerState() {
        boolean state = mScanManager.getTriggerLockState();
        return state;
    }

    /**
     * ScanManager.startDecode
     */
    private void startDecode() {
        if (!mScanEnable) {
            System.out.println("startDecode ignore, Scan enable:" + mScanEnable);
            return;
        }
        boolean lockState = getlockTriggerState();
        if (lockState) {
            System.out.println("startDecode ignore, Scan lockTrigger state:" + lockState);
            return;
        }
        if (mScanManager != null) {
            mScanManager.startDecode();
        }
    }

    /**
     * ScanManager.stopDecode
     */
    private void stopDecode() {
        if (!mScanEnable) {
            System.out.println("stopDecode ignore, Scan enable:" + mScanEnable);
            return;
        }
        if (mScanManager != null) {
            mScanManager.stopDecode();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        System.out.println("onPauseonPauseonPause");
        registerReceiver(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        initScan();
        registerReceiver(true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
